/**
 * Created by Administrator on 2018/5/4.
 */
var vc;
define(function (require,exports,module) {
    require("../../../lib/fullcalendar/fullcalendar.min.css");
    require("../../../lib/fullcalendar/scheduler.min.css");
    require("./scheduleTable.css")
    var sTpl = require("./template.html");
    var VueComponent = Vue.extend({
        props:['parentData'],
        template: sTpl,
        methods:{
            initQueryParam:function () {
                var mo =  moment();
                mo.week(mo.week()-1)
                var startDate =mo.format("YYYY-MM-DD");
                var mo2 =  moment();
                var endDate = mo2.week(mo2.week+1);
                var endDate = mo2.format("YYYY-MM-DD");
                this.startDate = startDate;
                this.endDate = endDate;

            },
            adjust:function (id) {
                this.adjustSchedule = this.schedule.find(function (val) {
                    return id==val.id;
                })
                this.adjustSchedule = JSON.parse(JSON.stringify(this.adjustSchedule));
                this.dialogTableVisible=true;
              //console.log(this.adjustSchedule);
            },
            removeItem:function (index) {
                var $this = this;
                this.$confirm('确定要移除该服务项？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'success'
                }).then(function(){
                    $this.adjustSchedule.schedulings.splice(index,1);
                })


            },
            addScheduling:function () {
              this.addItem =JSON.parse(JSON.stringify(this.emptyAddItem));
              this.addItem.addShow=true;


            },
            selectVehicle:function (val) {
                this.adjustItem.airSecurityVehiclePo = this .airSecurityVehicles.find(function (veh) {
                    return veh.airSecurityVehicleId ==val;
                })
            },
            adjustFwUser:function (sc,index) {
                if(sc.adjustUserShow==true){
                    sc.adjustUserShow=false;
                }else{
                    var $this = this;
                    this.adjustSchedule.schedulings.forEach(function (val,index) {
                        val.adjustUserShow =false;
                        $this.$set($this.adjustSchedule.schedulings,index,val);
                    })
                    sc.adjustUserShow=true;

                    var item =this.scheduleItems.find(function(val){return val.gsiId==sc.groundServiceItemPo.gsiId})
                    var selectAbleUser=[];item.teams.forEach(function(team){selectAbleUser=selectAbleUser.concat(team.userList) })
                    this.selectAbleFwUser = selectAbleUser;
                    this.selectedFwUser = sc.selectedFwUser;
                    this.adjustItem = sc;
                    this.adjuseVehicleId=sc.airSecurityVehiclePo.airSecurityVehicleId;
                    this .airSecurityVehicles = item.airSecurityVehicle;
                }
                this.$set(this.adjustSchedule.schedulings,index,sc)

            },
            closeUserAdjust:function(sc,index){
                sc.adjustUserShow=false;
                this.$set(this.adjustSchedule.schedulings,index,sc)
            },
            selectItem:function (nv,ov) {
              this.addItem.groundServiceItemPo = this.scheduleItems.find(function (val) {
                  return nv ==val.gsiId;
              })
                var selectAbleUser=[];
                this.addItem.groundServiceItemPo.teams.forEach(
                    function(team){
                        selectAbleUser=selectAbleUser.concat(team.userList)
                 });
                this.addItem.selectAbleFwUser = selectAbleUser;
            },
            teamChange:function (nv,ov) {
               var selectTeam=this.addItem.groundServiceItemPo.teams.find(function (val) {
                   return nv ==val.teamId;
               })
                this.addItem.selectedFwUser  = JSON.parse(JSON.stringify(selectTeam.userList));
            },
            confirmAdd:function () {
                this.addItem.addShow=false;
                this.adjustSchedule.schedulings.unshift(this.addItem)
            },
            queryFlightPlane:function () {
            },
            save:function () {
                var $this=this;
                axios.post(basepath+"/api/flightPlane/saveSchedules",this.adjustSchedule).then(function (response) {
                    $('#calendar').fullCalendar( 'refetchEvents' );
                    $this.dialogTableVisible=false;
                })
            },
             loadJs:function () {
                var $this = this;
                 require.async("../../../lib/fullcalendar/moment.min.js",function() {
                     require.async("../../../lib/fullcalendar/fullcalendar.js", function () {
                         require.async("../../../lib/fullcalendar/locale/zh-cn.js", function () {
                             require.async("../../../lib/fullcalendar/scheduler.min.js", function () {
                                 $this.jsLoading=false;
                             })
                         })
                     })
                 })

              }

        },
        watch:{
            jsLoading:function(ov,nv){

                var a = moment();
                var $this = this;
                var fullCalendar= $('#calendar').fullCalendar({
                    now: a.format("YYYY-MM-DD"),
                    slotEventOverlap:true,
                    height: "auto",
                    allDayDefault:false,
                    allDaySlot:false,
                    editable: false, // enable draggable events
                    aspectRatio: 1.8,
                    displayEventTime:true,
                    agendaEventMinHeight:20,
                    scrollTime: '00:00', // undo default 6am scrollTime
                    header: {
                        left: 'today prev,next',
                        center: 'title',
                        right: 'agendaDay,agendaWeek ,month'
                    },
                    defaultView: 'agendaWeek',
                    views: {
                        basic: {
                            groupByDateAndResource :true,
                        }
                            // options apply to basicWeek and basicDay views
                        },
                        agenda: {

                            allDayDefault:false
                            // options apply to agendaWeek and agendaDay views
                        },
                        week: {
                            // options apply to basicWeek and agendaWeek views
                        },
                        day: {
                            slotDuration:'00:30:00'
                        },
                    // eventTextColor:"#333",
                    // eventBackgroundColor:"rgba(0,0,0,0.02)",
                    slotLabelInterval:'01:00:00',
                    slotDuration:'00:30:00',
                    resourceLabelText: '航班',

                    //     function(callback, start, end, timezone){
                    //     resourceCallback= callback;
                    // },
                    events:function( start, end, timezone, callback ){
                        // console.log(start);
                        // console.log(end);

                        var startDate =start.format("YYYY-MM-DD");
                        var endDate = end.format("YYYY-MM-DD");
                        var url=basepath+"/api/flightPlane/queryScheded?startDate="+startDate+"&scheduled=true"
                            +"&endDate="+endDate+"&flightInfoId="//+($this.flightInfoId?$this.flightInfoId:"");
                        this.url=url;

                        axios.get(url).then(function (response) {
                            needPush = [];
                            var days = {};
                            var num=0;
                            $this.schedule = response.data;
                            response.data.forEach(function (val) {
                                val.title=val.flightPlanePo.flightInfo.flightNum;
                                var startTime;
                                val.schedulings.forEach(function(data){
                                    num++;
                                    if(val.flightPlanePo.importOrExport=="进港"){
                                        var start = moment(val.flightPlanePo.arriveTime);
                                        data.start = start.minute(start.minute()+data.groundServiceItemPo.importDifference)
                                    }
                                    if(val.flightPlanePo.importOrExport=="出港"){
                                        var start = moment(val.flightPlanePo.takeOffTime);
                                        data.start = start.minute(start.minute()-data.groundServiceItemPo.exportDifference)
                                    }
                                    if(val.flightPlanePo.importOrExport=="中转联程"){
                                        var baseTime = data.groundServiceItemPo.transferProcessStrategy=="takeOffTime"?val.flightPlanePo.takeOffTime:val.flightPlanePo.arriveTime;
                                        var start = moment(baseTime);
                                        data.start = data.groundServiceItemPo.transferProcessStrategy=="takeOffTime"?start.minute(start.minute()-data.groundServiceItemPo.transferProcessDifference):start.minute(start.minute()+data.groundServiceItemPo.transferProcessDifference)

                                    }
                                    if(data.start){
                                        data.start = data.start.format("YYYY-MM-DD HH:mm:ss");
                                    }else{
                                        console.log(123);
                                    }


                                    startTime=startTime?startTime:data.start;
                                    startTime=startTime<data.start?startTime:data.start;
                                });
                                val.start = startTime;//val.flightPlanePo.takeOffTime;
                                 val.end = moment(new Date(val.start).getTime()+1000).format("YYYY-MM-DD HH:mm:ss");
                                // val.resourceId="a"+moment(val.start).format("HH");
                                if(!days[moment(val.start).format("YYYY-MM-DD")] ){
                                    days[moment(val.start).format("YYYY-MM-DD")] =true;
                                    var id= moment(val.start).format("YYYY-MM-DD");
                                    var start =id +" 23:59:58";
                                    var end = id +" 23:59:59";
                                    needPush.push({start:start,end:end,id:end ,endData:true});
                                }


                            })
                            console.log(num);
                            callback(response.data.concat(needPush));
                        });

                     }

                     //
                        //[{"title":"Long Event","start":"2018-08-07","end":"2018-08-10"},{"id":999,"title":"Repeating Event","start":"2018-08-09T16:00:00+00:00"},{"title":"Conference","start":"2018-08-08","end":"2018-08-10"},{"title":"Meeting","start":"2018-08-09T10:30:00+00:00","end":"2018-08-09T12:30:00+00:00"},{"title":"Lunch","start":"2018-08-09T12:00:00+00:00"},{"title":"Birthday Party","start":"2018-08-10T07:00:00+00:00"}]

                     //,
                     // resourceRender: function(resource, labelTds, bodyTds) {
                    //
                    //     labelTds.find(".fc-cell-content").html("<div>"+resource.title+"</div><div>"+resource.flightPlane.originating+
                    //         "-"+resource.flightPlane.destination+"</div>"+"<div>起飞："+moment(resource.flightPlane.takeOffTime).format("HH:mm")+"</div><div>落地："
                    //         +moment(resource.flightPlane.arriveTime).format("HH:mm")+"</div>")
                    // }
                    ,eventRender: function(event, element) {
                         console.log(event);
                        if(event.endData){
                            element.html("<div></div>");
                        }else{
                            var info = "";
                            event.schedulings.forEach(function(val){
                                info+="<div >"
                                info+="<h5>"+val.groundServiceItemPo.itemName+":</h5>"
                                info+="<div> <div class='car-title'>人员：</div>"
                                val.selectedFwUser.forEach(function (user) {
                                    info+="<span class='user-name'>"+user.userCnName+"</span>";
                                })
                                info+="</div>";
                                if(val.airSecurityVehiclePo){
                                    info+="<div class='car-title'>保障车：</div><span class='carInfo'>"+val.airSecurityVehiclePo.vehicleType+"-"+val.airSecurityVehiclePo.vehicleNum+"</span><span class='carInfo'></span>"
                                }
                                info+="</div>";
                            })
                            info+="<div><div class='button' onclick=adjust('"+event.id+"') >调整</div></div>"

                            if(event.start.format("E")==7||event.start.format("E")==6){
                                element.html("<input type='radio' name='event-title-info' id='"+event.id+"' class='event-title-info' /> <div class='event-container'><label for='"+event.id+"' class='event-title' onclick='check(this)'>"+moment(event.start).format("HH:mm")+":"+event.title+"</label><div class='event-info weekend'><div class='x-arrow'></div><div class='info-container'><div class='info-context'>"+info+"</div></div></div></div>");
                            }else{
                                element.html("<input type='radio' name='event-title-info' id='"+event.id+"' class='event-title-info' /> <div class='event-container'><label for='"+event.id+"' class='event-title' onclick='check(this)'>"+moment(event.start).format("HH:mm")+":"+event.title+"</label><div class='event-info'><div class='x-arrow'></div><div class='info-container'><div class='info-context'>"+info+"</div></div></div></div>");
                            }

                        }

                    }
                });

            }
        },
        data:function () {
            return {
                airSecurityVehicles:[],
                adjustItem:{},
                adjuseVehicleId:'',
                emptyAddItem:{
                    addShow:false,
                    airSecurityVehiclePo:null,
                    groundServiceItemPo:{},
                    selectedFwUser:[],
                    selectedTeamId:"",
                    status:"发布",
                    gsiId:"",},
                addItem:{
                },
                adjustUserShow:false,
                selectAbleFwUser:[],
                selectedFwUser:[],
                startDate:"",
                endDate:"",
                flightInfoId:"",
                schedule:[],
                scheduleItems:[],
                adjustSchedule:[],
                flightPlane:[],
                jsLoading:true,
                dialogTableVisible:false
            };
        },
        mounted:function () {
            this.loadJs();
            var $this = this;
            axios.get(basepath+"/api/flightPlane/queryAllScheduleItem").then(function (response) {
                $this.scheduleItems =response.data;
            })
        }
        ,
        created:function (){
            vc = this;

            var resourceCallback ;
            // require.async("../../../lib/fullcalendar/moment.min.js",function(){
            //     require.async("../../../lib/fullcalendar/fullcalendar.js",function(){
            //         require.async("../../../lib/fullcalendar/locale/zh-cn.js",function(){
            //             require.async("../../../lib/fullcalendar/scheduler.min.js",function(){
            //             //start
            //
            //             setTimeout(function () {
            //
            //
            //
            //
            //
            //
            //
            //
            //
            //
            //
            //
            //
            //             })
            //
            //
            //             //end
            //             });
            //         });
            //         });
            //     });

        },
        activated:function () {
            messages.$emit('change','地服排班表');
        }
    });

    module.exports = VueComponent;
    return VueComponent;
})

function check($this){
    var id= $this.getAttribute("for");
    var input= document.getElementById(id);
    if(input.checked==true){
        setTimeout(function () {
            input.checked = false;
        })
    }
    console.log(input)

}
function adjust(id) {
    vc.adjust(id);
}